import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:zrjz/comm/utils/util.dart';
import 'package:zrjz/comm/widget/dialog/app_default_dialog.dart';
import 'package:zrjz/globalService/user_service.dart';
import 'package:zrjz/modules/auth/login/login_page.dart';

/*
 * 特殊状态code处理的拦截器，
 * 401 弹出弹窗提示用户重新登录
 */
class StatusCodeDioInterceptors extends Interceptor {

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    bool isDialogShowing = false; // 控制弹窗是否正在显示
    if (response.statusCode == 401) {
      // 避免重复展示弹窗
      if (!isDialogShowing) {
        //弹框就清除了数据
        UserService.to.handleLogoutParams();

        //拦截 token 过期，弹出弹窗提示用户重新登录
        SmartDialog.show(
          usePenetrate: false,
          debounce: true,
          keepSingle: true,
          clickMaskDismiss: false,
          onDismiss: () {
            isDialogShowing = false;
          },
          builder: (context) => AppDefaultDialog(
            "登录凭证已过期，请重新登录",
            confirmAction: () {
              LoginPage.offAllNamed();
            },
          ),
        );
        //设置已经展示
        isDialogShowing = true;
      }
    }
    super.onResponse(response, handler);
  }

  @override
  Future onError(DioException err, ErrorInterceptorHandler handler) async {
    super.onError(err, handler);
  }
}
